import random
import re
from flask import current_app, jsonify
from flask import make_response
from flask import request
from info import constants
from info import redis_store
from info.libs.yuntongxun.sms import CCP
from info.models import User
from info.response_code import RET
from info.utils.captcha.captcha import captcha
from . import passport_blu


# 获取图片验证码
@passport_blu.route('/image_code')
def get_image_code():
    # 获取编码
    code_id = request.args.get('code_id', None)

    # 生成编码
    name, text, image = captcha.generate_captcha()

    try:
        redis_store.set("ImageCode_"+code_id, text, constants.IMAGE_CODE_REDIS_EXPIRES)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(error=RET.DATAERR, errmsg='保存图片验证码失败')

    resp = make_response(image)
    resp.headers["Content-Type"] = "image/jpg"
    return resp


# 短信验证码
@passport_blu.route("/smscode")
def send_sms():
    """
    1. 接收参数并判断是否有值
    2. 校验手机号是正确
    3. 通过传入的图片编码去redis中查询真实的图片验证码内容
    4. 进行验证码内容的比对
    5. 生成发送短信的内容并发送短信
    6. redis中保存短信验证码内容
    7. 返回发送成功的响应
    :return:
    """
    mobile = request.json.get("mobile")  # 手机号
    image_code = request.json.get("image_code")  # 图片验证码内容
    image_code_id = request.json.get("image_code_id")  # 图片验证码编号

    if not all(["mobile", "image_code", "image_code_id"]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数不足")

    if not re.match("^1[3578]([0-9]{9})", mobile):
        return jsonify(errno=RET.DATAERR, errmsg="手机号错误")

    try:
        image_content = redis_store.get("ImageCode_" + image_code_id)
        if image_code:
            redis_store.delete("ImageCode_" + image_code_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询失败")

    if not image_content:
        return jsonify(errno=RET.NODATA, errmsg="图片验证码已过期")

    if image_content.upper() != image_code.upper:  # 字母都转大写
        return jsonify(errno=RET.DATAERR, errmsg="图片验证码输入错误")

    try:
        user = User.query.filter(User.mobile == mobile).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询失败")

    if user:
        return jsonify(errno=RET.DATAEXIST, errmsg="该手机已经注册")

    # 发送短信验证码
    result = random.randint(0, 999999)
    sms_code = "%06d" %result
    current_app.logger.debug("短信验证码的内容是：%s" % sms_code)
    result = CCP().send_template_sms(mobile, [sms_code, int(constants.SMS_CODE_REDIS_EXPIRES/60)], "1")
    if result !=0:
        return jsonify(errno=RET.THIRDERR, errmsg="发送短信失败")

    # 保存短信验证码
    try:
        redis_store.set("SMS_" + mobile, sms_code, constants.SMS_CODE_REDIS_EXPIRES)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="保存短信验证码失败")

    return jsonify(errno=RET.OK, errmsg="发送成功")